package com.wwm.springcloud.authservice.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;

/**
 * 自定义明文密码加密
 */
public class BwPasswordEncoder extends MessageDigestPasswordEncoder
{
    private static Logger logger = LoggerFactory.getLogger(BwPasswordEncoder.class);

    public BwPasswordEncoder(String algorithm)
    {
        super(algorithm);
    }

    public BwPasswordEncoder(String algorithm, boolean encodeHashAsBase64) throws IllegalArgumentException
    {
        super(algorithm, encodeHashAsBase64);
    }

    /**
     * 实现加密的方法，既将明文转换为密文的方法
     * @param rawPass
     * @param salt
     * @return
     * @throws DataAccessException
     */
    @Override
    public String encodePassword(String rawPass, Object salt) throws DataAccessException
    {
        String pass = null;
        if (null == salt)
        {
            return null;
        }
        try
        {
//            pass = PasswordUtils.getUuidPasswd(rawPass, salt.toString());
            //2017-8-22 密码加密方式改为客户端加密，所以此处不需要再进行加密操作
            pass = rawPass;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return pass;
    }

    /**
     * 验证密码是否有效的方法，返回'true'则登录成功
     * @param savePass
     * @param submitPass
     * @param salt
     * @return
     * @throws DataAccessException
     */
    @Override
    public boolean isPasswordValid(String savePass, String submitPass, Object salt) throws DataAccessException
    {
        return savePass.equalsIgnoreCase(encodePassword(submitPass, salt));
    }
}